/*
 * Config
 * 
 * Version information
 * 
 * Feb 17, 2006
 * 
 * Copyright (c) AmSoft Systems, 2006
 */
package net.amsoft.iservice.isso.webapp.struts.action;

import static net.amsoft.iservice.isso.util.ISSOConstants.SENDER_NAME;
import static net.amsoft.iservice.util.IServiceConstants.*;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.amsoft.iservice.isso.service.ISSOService;
import net.amsoft.iservice.isso.webapp.dataObject.LoginData;
import net.amsoft.iservice.isso.webapp.dataObject.SPData;
import net.amsoft.iservice.isso.webapp.struts.form.ConfigForm;
import net.amsoft.iservice.isso.util.ISSOConstants;
import net.amsoft.iservice.util.EmailService;
import net.amsoft.iservice.util.IServiceConstants;
import net.amsoft.iservice.util.IServiceUtil;
import net.amsoft.iservice.util.exception.IServiceException;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 * This will save receive and save the edited service configuration parameter
 * 
 * @author rahul
 */
public class Config extends BaseAction {
	private static final Logger oLogger = Logger.getLogger(Config.class);

	public ActionForward process(ActionMapping oMapping, ActionForm oForm,
			HttpServletRequest oRequest, HttpServletResponse oResponse)
			throws Exception {
		oLogger.info("process() : entry");
		LoginData oLoginData = (LoginData) oRequest.getSession(false)
				.getAttribute(ISSOConstants.SESSION_LOGIN_OBJ);

		// Forward to Login page if not logged in
		if (oLoginData.isLoginStatus() == false) {
			oLogger.warn("process() : Message : Login status is false");
			return oMapping.findForward(ISSOConstants.CHKLOGIN_FWD);
		}

		String sStep = oRequest.getParameter(ISSOConstants.REQ_PARAM_STEP);
		oLogger.info("process() : Request Param=" + sStep);
		// Check if parameter is null due to direct access of page
		if (sStep != null) {
			if (ISSOConstants.REQ_PARAM_STEP_VALUES.equals(sStep)) {
				return save(oMapping, oForm, oRequest);
			} else {
				return cancel(oMapping, oForm, oRequest);
			}
		} else {
			return oMapping.findForward(ISSOConstants.CHKLOGIN_FWD);
		}
	}

	/**
	 * Perform the save opertaion of principal configuration and returns the
	 * appropriate action forward
	 * 
	 * @param oMapping
	 * @param oForm
	 * @param oRequest
	 * @return Welcome page: if save operation succeeds, otherwise returns to
	 *         same page
	 * @throws Exception
	 */
	private ActionForward save(ActionMapping oMapping, ActionForm oForm,
			HttpServletRequest oRequest) throws Exception {
		IServiceUtil.log(INFO, this, "save() entry");
		ActionMessages oMsgs = new ActionErrors();
		try {
			LoginData oLoginData = (LoginData) oRequest.getSession(false)
					.getAttribute(ISSOConstants.SESSION_LOGIN_OBJ);
			ConfigForm oConfigData = (ConfigForm) oForm;
			HashMap ohSPData = (HashMap) oRequest.getSession(false)
					.getAttribute(ISSOConstants.SESSION_LOGIN_HASH_OBJ);

			String sSpXri = ISSOConstants.getSPXri(oRequest.getServerName());
			SPData oSPData = (SPData) ohSPData.get(sSpXri);
			if (oSPData == null) {
				oMsgs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
						ISSOConstants.ERR_INVALID_REQUEST));
				saveErrors(oRequest, oMsgs);
				oLogger.debug("process() : Data : SPData=" + oSPData);
				oLogger
						.error("process() : Message : Service could not be identified, forward to iname page");
				return oMapping.findForward(ISSOConstants.INAME_FWD);
			}

			String sGlobalInumber = oSPData.getGlobalInumber();
			String sSessionCookie = oLoginData.getSessionCookie();

			// Check if "Change Password" is checked
			if (oConfigData.isChangePassword()) {
				ISSOService.updatePassword(sGlobalInumber, sSessionCookie,
						oConfigData.getOldPassword(), oConfigData
								.getNewPassword());
				// Notify user about password change
				notifyUser(sGlobalInumber, oRequest.getScheme() + "://"
						+ oRequest.getServerName(), oRequest.getLocale(),
						oConfigData.getEmailAddress());
			}
			oLogger.info("save() : Message : Password updated");

			// Update FirstName, LastName and EmailAddress
			ISSOService.updatePrincipalProfile(sGlobalInumber, sSessionCookie,
					oConfigData.getFirstName(), oConfigData.getLastName(),
					oConfigData.getEmailAddress());
			oLogger.info("save() : Message : Principal profile updated");

			// Update Challenge answer only if check box value is true
			String sChallenegeAnswer = null;
			int iChallengeQuestion = -1;

			if (oConfigData.isChangeAnswer()) {
				sChallenegeAnswer = oConfigData.getChallengeAnswer();
				iChallengeQuestion = Integer.parseInt(oConfigData
						.getChallengeQuestion());
			}
			ISSOService.updatePrincipalSecurityInfo(sGlobalInumber,
					sSessionCookie, oConfigData.getGreeting(),
					iChallengeQuestion, sChallenegeAnswer);
			oLogger.info("save(): Message : Principal Security info updated");

			oMsgs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
					ISSOConstants.MSG_CONFIG_SAVED));
			saveErrors(oRequest, oMsgs);
			oLogger.info("save() : Exit, Forward to Check login");
			return oMapping.findForward(ISSOConstants.CHKLOGIN_FWD);
		} catch (IServiceException oIServExp) {
			ResourceBundle oBundle = ResourceBundle.getBundle("issoResources",
					oRequest.getLocale());
			// Get the invalid e-mail msg from resource bundle
			if (oIServExp.getErrorCode() == 1000) {
				String sEmailMsg = oBundle
						.getString(ISSOConstants.ERR_INVALID_EMAIL);
				oMsgs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
						sEmailMsg, false));
			} else if (oIServExp.getErrorCode() == 1001) {
				oMsgs
						.add(
								ActionMessages.GLOBAL_MESSAGE,
								new ActionMessage(
										oBundle
												.getString(ISSOConstants.ERR_WRONG_EXISTING_PWD),
										false));
			} else {
				oMsgs.add(ActionMessages.GLOBAL_MESSAGE,
						new ActionMessage(ISSOConstants.getError(oIServExp
								.getErrorCode()), false));
			}

			saveErrors(oRequest, oMsgs);
			oLogger.error("save() : Exit, Forward to Input page");
			return oMapping.getInputForward();
		}
	}

	private void notifyUser(String sGlobalInumber, String sSSOUrl,
			Locale locale, String sEmail) {
		oLogger.info("notifyUser() : entry with data : GIN :" + sGlobalInumber
				+ ", SSOUrl :" + sSSOUrl + ", email :" + sEmail);
		ResourceBundle oBundle = ResourceBundle.getBundle("issoResources",
				locale);
		String sDefaultFromAddr = IServiceConstants.ISERVICE_BUNDLE
				.getString(IServiceConstants.EMAIL_FROM);
		String sPattern = oBundle
				.getString(ISSOConstants.EMAIL_CHNG_PWD_BODY);
		Object[] params = { sGlobalInumber, sSSOUrl };
		String sCompleteMsg = MessageFormat.format(sPattern, params);
		oLogger.info("notifyUser() : EMail Message : "+sCompleteMsg);
		
		ArrayList<String> alRecepientList = new ArrayList<String>();
		alRecepientList.add(sEmail);
		// Create email object
		EmailService oEmailService = new EmailService();
		oEmailService.setFromAddress(sDefaultFromAddr);
		oEmailService.setReplyToAddress(sDefaultFromAddr);
		oEmailService.setName(oBundle.getString(SENDER_NAME));

		oEmailService.setReceipientList(alRecepientList);
		oEmailService.setBody(sCompleteMsg);
		oEmailService.setSubject(oBundle
				.getString(ISSOConstants.EMAIL_CHNG_PWD_SUB));
		oEmailService.sendMail();
		oLogger.info("notifyUser() : exit, email for password change is sent");
	}

	private ActionForward cancel(ActionMapping oMapping, ActionForm oForm,
			HttpServletRequest oRequest) {
		oLogger.info("cancel() : entry");
		ActionMessages oMessages = new ActionErrors();
		oMessages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
				ISSOConstants.MSG_CONFIG_CANCELED));
		saveErrors(oRequest, oMessages);
		oLogger.info("cancel() : Exit, Forward to Check login");
		return oMapping.findForward(ISSOConstants.CHKLOGIN_FWD);
	}
}
